
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* swapPairs(struct ListNode* head) {
    // 创建一个虚拟节点 dummy，并将其指向 head
    struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummy->next = head;
    struct ListNode* prev = dummy;

    // 遍历链表，每两个结点进行交换
    while (head && head->next) {
        struct ListNode* first = head;
        struct ListNode* second = head->next;

        // 交换结点
        prev->next = second;
        first->next = second->next;
        second->next = first;

        // 更新 prev 和 head 的指向
        prev = first;
        head = first->next;
    }

    return dummy->next;
}

int main() {
    // 创建链表：1->2->3->4->5
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->val = 1;
    head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next->val = 2;
    head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next->next->val = 3;
    head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next->next->next->val = 4;
    head->next->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next->next->next->next->val = 5;
    head->next->next->next->next->next = NULL;

    // 交换链表中的结点
    struct ListNode* newHead = swapPairs(head);

    // 打印交换后的链表
    while (newHead) {
        printf("%d ", newHead->val);
        newHead = newHead->next;
    }

    return 0;
}

